package com.alibaba.citrus.cr.order.open.api.facade.service;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.order.open.api.facade.common.until.CheckUtil;
import com.alibaba.citrus.cr.unified.inventory.facade.service.AllocateApplyOrderReadServiceImpl;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mninventorycenter.model.dto.*;
import com.epoch.app.mninventorycenter.planorderreadservice.service.PlanOrderReadServiceService;
import com.epoch.app.mninventorycenter.service.MnInventoryCenterService;
import groovy.util.logging.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PlanOrderReadServiceServiceImpl  implements PlanOrderReadServiceService {

    Log log = Log.getLogger(AllocateApplyOrderReadServiceImpl.class);


    @Resource
    private MnInventoryCenterService mnInventoryCenterService;

    private static final String FROM_SYS_GROUP = "fromSys";
    private static final String BUSINESS_TYPE_GROUP = "businessType";

    @Override
    @FacadeInvoker(value = "分页查询计划单")
    public Result<List<BusinessPlanOrderPageResponse>> queryBusinessPlanOrderPage(BusinessPlanOrderQueryRequest businessPlanOrderQueryRequest) {

        log.info("PlanOrderReadServiceService.queryBusinessPlanOrderPage.request:{}", JSONObject.toJSONString(businessPlanOrderQueryRequest));

        String message = checkQueryBusinessPlanOrderPage(businessPlanOrderQueryRequest);

        if(message != null){
            return Result.fail("10000",message);
        }

        Result<List<BusinessPlanOrderPageResponse>> result = mnInventoryCenterService.queryPlanOrderListPage(businessPlanOrderQueryRequest);
        log.info("PlanOrderReadServiceService.queryBusinessPlanOrderPage.response:{}", JSONObject.toJSONString(result));

        if(result == null){
            return Result.success(Collections.emptyList());
        }
        List<BusinessPlanOrderPageResponse> planOrderPageResponses = result.getResult();
        if(CollectionUtils.isEmpty(planOrderPageResponses)){
            return Result.success(Collections.emptyList());
        }
        // 组装系统来源业态名称
        /*List<String> businessList = planOrderPageResponses.stream().map(BusinessPlanOrderPageResponse::getBusinessType).collect(Collectors.toList());
        List<String> fromList = planOrderPageResponses.stream().map(BusinessPlanOrderPageResponse::getFromSys).collect(Collectors.toList());*/
        Map<String, String> businessMap = getDictionaryDataListApi("businessType");
        Map<String, String> fromSysMap = getDictionaryDataListApi("fromSys");
        planOrderPageResponses.forEach( x ->{
            x.setBusinessTypeName(businessMap.get(x.getBusinessType()));
            x.setFromSysName(fromSysMap.get(x.getFromSys()));
        });
        result.setResult(planOrderPageResponses);
        return result;
    }

    private Map<String, String> getDictionaryDataListApi(String group) {
        DictionaryQueryRequest request = new DictionaryQueryRequest();
        request.setGroup(group);
        log.info("getDictionaryDataListApi,group:{}",group);
        Result<List<DictionaryResponse>> result = mnInventoryCenterService.queryDictionaryDataListApi(request);
        log.info("getDictionaryDataListApi,result:{}", JSON.toJSON(result));
        if(CollectionUtils.isEmpty(result.getResult())){
            return new HashMap<>();
        }
        return result.getResult().stream()
                .collect(Collectors.toMap(DictionaryResponse::getCode, DictionaryResponse::getName, (value1,value2) -> value1));
    }
    private String  checkQueryBusinessPlanOrderPage(BusinessPlanOrderQueryRequest planOrderQueryRequest) {

        // epochPage不为空不需要传系统来源，业态
        if(StringUtils.isNotBlank(planOrderQueryRequest.getEpochPage())){
            return null;
        }
        if(StringUtils.isBlank(planOrderQueryRequest.getBusinessType())){
            return "业态不能为空";
        }
        if(planOrderQueryRequest.getBusinessType().length() > 32){
            return "业态字段长度大于32";
        }
        if(StringUtils.isBlank(planOrderQueryRequest.getFromSys()) ){
            return "系统来不能为空";
        }
        if( planOrderQueryRequest.getFromSys().length() > 32){
            return "系统来源字段长度大于32";
        }
        if (!checkDictionary(FROM_SYS_GROUP,planOrderQueryRequest.getFromSys())){
            return "系统来源错误";
        }
        if (!checkDictionary(BUSINESS_TYPE_GROUP,planOrderQueryRequest.getBusinessType())){
            return "业态错误";
        }
        if(CollectionUtils.isNotEmpty(planOrderQueryRequest.getFactoryCodes())){
            if(planOrderQueryRequest.getFactoryCodes().size() > 50){
                return "工厂编码元素个数大于50";
            }
            if(CollectionUtils.isNotEmpty(planOrderQueryRequest.getFactoryCodes().stream().filter(x->x.length()>32).collect(Collectors.toList()))){
                return "工厂编码字段长度大于32";
            }
        }
        if(CollectionUtils.isNotEmpty(planOrderQueryRequest.getGoodstCodes())){
            if(planOrderQueryRequest.getGoodstCodes().size() > 50){
                return "货品编码元素个数大于50";
            }
            if(CollectionUtils.isNotEmpty(planOrderQueryRequest.getGoodstCodes().stream().filter(x->x.length()>32).collect(Collectors.toList()))){
                return "货品编码字段长度大于32";
            }
        }
        if(StringUtils.isNotBlank(planOrderQueryRequest.getGoodsName()) && planOrderQueryRequest.getGoodsName().length() > 50){
            return "货品名称字段长度大于50";
        }
        return  null;
    }
    /**
     * 校验字典
     * @param group group
     * @param code code
     * @return boolean
     */
    private boolean checkDictionary(String group, String code) {
        DictionaryQueryRequest request = new DictionaryQueryRequest();
        request.setGroup(group);
        Result<List<DictionaryResponse>> result = mnInventoryCenterService.queryDictionaryDataListApi(request);
        Set<String> businessTypeSet = result.getResult().stream()
                .map(DictionaryResponse::getCode)
                .collect(Collectors.toSet());
        return businessTypeSet.contains(code);
    }


    /**
     * 工厂+货品+生产日期+单位
     * @param queryPlanOrderListRequest req
     * @return list
     */
    @Override
    @FacadeInvoker(value = "查询计划单")
    public Result<List<BusinessPlanOrderListResponse>> queryBusinessPlanOrderList(QueryPlanOrderListRequest queryPlanOrderListRequest){
        checkQueryBusinessPlanOrderList(queryPlanOrderListRequest);
        return mnInventoryCenterService.queryPlanOrderList2(queryPlanOrderListRequest);
    }

    private void checkQueryBusinessPlanOrderList(QueryPlanOrderListRequest queryPlanOrderListRequest) {
        if(StringUtils.isBlank(queryPlanOrderListRequest.getFromSys())){
            throw new FacadeException(ErrorMessage.code("系统来源入参异常"));
        }
        if(StringUtils.isBlank(queryPlanOrderListRequest.getBusinessType())){
            throw new FacadeException(ErrorMessage.code("业态入参异常"));
        }
    }
}
